package com.mall.untils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by konglinghui on 15/6/12.
 */
public class ChangeAudioFormat {

    /**
     * 将上传的录音转为mp3格式
     *
     * @param targetPath
     * @param sourcePath 文件的相对地址
     */
    public static int ToMp3(String sourcePath, String targetPath) {
        Runtime run = null;
        try {
            run = Runtime.getRuntime();

            System.out.println("sudo ffmpeg -i " + sourcePath + " -acodec libmp3lame " + targetPath);

            Process p = run.exec("sudo ffmpeg -i " + sourcePath + " -acodec libmp3lame " + targetPath);//执行ffmpeg.exe,前面是ffmpeg.exe的地址，中间是需要转换的文件地址，后面是转换后的文件地址。-i是转换方式，意思是可编码解码，mp3编码方式采用的是libmp3lame

            //读取屏幕输出
            BufferedReader strCon = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = strCon.readLine()) != null) {
                System.out.println(line);
            }

            //释放进程
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();

//            //删除原来的文件
//            if (file.exists()) {
//                file.delete();
//            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            //run调用lame解码器最后释放内存
            run.freeMemory();
        }

        return 1;
    }
}
